﻿# -*- coding: utf-8 -*-
# Add parent folder to sys.path, so we can import boot.
# App Engine causes main.py to be reloaded if an exception gets raised
# on the first request of a main.py instance, so don't add parent_dir multiple
# times.

#-----
from waveapi import events
from waveapi import robot
from waveapi import appengine_robot_runner
from google.appengine.api import memcache

from DBController import *
import passwords
import logging

def OnWaveletSelfAdded(event, wavelet):
  """Invoked when the robot has been added."""
  db_controller.put(wavelet)
  if not memcache.set("has_changes", True):
      memcache.add("has_changes", True)   

def OnWaveletTagsChanged(event, wavelet):
  db_controller.delete(wavelet.wave_id)  
  db_controller.put(wavelet)
  if not memcache.set("has_changes", True):
      memcache.add("has_changes", True)  
  
def OnWaveletSelfRemoved(event, wavelet):
  db_controller.delete(wavelet.wave_id)
  has_changes = True
  if not memcache.set("has_changes", True):
      memcache.add("has_changes", True)  

def OnWaveletTitleChanged(event, wavelet):
  logging.error("WaveletTitleChanged called!!!")

if __name__ == '__main__':
  myRobot = robot.Robot(passwords.ROBOT_NAME,
      image_url = passwords.IMAGE_URL,
      profile_url = passwords.PROFILE_URL)
  myRobot.setup_oauth(passwords.CONSUMER_KEY, passwords.CONSUMER_SECRET,\
    server_rpc_base='http://www-opensocial.googleusercontent.com/api/rpc')
  #-------------------------
  db_controller = memcache.get("db_controller")
  if not db_controller:
    db_controller = DBController()
    if not memcache.add("db_controller", db_controller, 600):
      logging.error("Memcache [db_controller] set failed.")
  #-------------------------
  myRobot.register_handler(events.WaveletSelfAdded, OnWaveletSelfAdded)
  myRobot.register_handler(events.WaveletTagsChanged, OnWaveletTagsChanged)
  myRobot.register_handler(events.WaveletSelfRemoved, OnWaveletSelfRemoved)
  myRobot.register_handler(events.WaveletTitleChanged, OnWaveletTitleChanged, 
                           context = events.Context.ALL)

  appengine_robot_runner.run(myRobot)